import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import { Spin, message, Button, Card, Alert, Form, Input, Upload, Icon, Row, Col } from 'antd';
import styles from './index.less';
import router from 'umi/router';

const namespace = 'paysetting';
@Form.create()
class XcxPay extends Component {
  componentWillMount() {
    window.Isoption = false;
    const { dispatch } = this.props;
    dispatch({
      type: `xcxauth/GetAuthStatus`,
      callback: {
          success: (data) => {
              if (data.Code !== 0) {
                  router.replace({
                      pathname: `/${window.storeId}/wechat/miniapp`,
                  });
              } else {
                this.GetInfo();
              }
          }
      }
    });
  }
  componentDidMount() {
    window.Isoption = true;
  }
  GetInfo = () => {
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/GetPayConfig`,
      param: { p: Math.random() },
    });
  };
  getbase64 = (info, callback) => {
    let reader = new FileReader();

    reader.readAsDataURL(info.file.originFileObj);
    reader.onload = () => {
      console.log(reader.result);
      let index = reader.result.lastIndexOf(',') + 1;
      let base = reader.result.substring(index, reader.result.length);
      callback(base);
    };
  };
  handleChange = info => {
    if (info.file.status === 'done') {
      this.getbase64(info, this.setCert);
    }
  };
  setCert = result => {
    const { setFieldsValue } = this.props.form;
    setFieldsValue({ CertFile: result });
  };

  handleSubmit = () => {
    let { dispatch } = this.props;

    this.props.form.validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: `${namespace}/SetPayConfig`,
          param: values,
          callBack: {
            success: data => {
              message.success('设置成功');
            },
            error: data => {
              message.error(data.Msg);
            },
          },
        });
      }
    });
  };
  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 3 },
        sm: { span: 3 },
        md: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 8 },
        sm: { span: 8 },
        md: { span: 8 },
      },
    };
    const {
      getFieldDecorator,
      getFieldsError,
      getFieldError,
      isFieldTouched,
      getFieldValue,

    } = this.props.form;
    const {
      paysetting: { info },
      loading,
      loadbtn,
    } = this.props;

    return (
      <Fragment>
        <Spin spinning={loading}>
          <Alert message={<span>第一次配置？查看<a>帮助文档</a></span>} type="info" showIcon />
          <Card className={styles.XdkwxInfo}>
            <Form >
            {/* <Form.Item
                {...formItemLayout}
                label="AppId"
              >
                <Input disabled value="wdssssdf"/>
                <div className="info">APPID（小程序ID），微信小程序后台开发与管理获取</div>
              </Form.Item> */}
              <Form.Item
                {...formItemLayout}
                label="商户号"
              >
                {getFieldDecorator('MchId', {
                  initialValue: info && info.MchId,
                  rules: [{ required: true, message: '商户号必填' }],
                })(<Input />)}
                <div className="info">微信支付商户号MCH_ID，审核通过后，在微信发送的邮件中查看</div>
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                label="商户密钥"
              >
                {getFieldDecorator('MchKey', {
                  initialValue: info && info.MchKey,
                  rules: [{ required: true, message: '商户密钥必填' }],
                })(<Input />)}
                <div className="info">商户支付密钥Key，请登录 微信支付商户平台，在【账户设置-安全设置-API安全】中设置</div>
              </Form.Item>
              <Form.Item {...formItemLayout} label="" help="">
                {getFieldDecorator('CertGzh', {
                  initialValue: info && info.CertBase64,
                  rules: [],
                })(<Input type="hidden" />)}
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                label="支付证书"
                help="请使用扩展名为p12的证书文件"
                className={styles.UpText}
              >
                {getFieldDecorator('CertFile', {
                  rules: [],
                })(
                  <Upload accept=".p12" onChange={this.handleChange}>
                    <Button>选择文件</Button>
                  </Upload>
                )}
              </Form.Item>
              <Row>
                <Col offset={3}>
                  {
                    getFieldValue('CertGzh') ? <div className={styles.UpTip}>
                      <Icon type="check-circle" theme="filled" />
                      证书已上传，可再次上传
                  </div> : null
                  }
                </Col>
              </Row>

              <Form.Item {...formItemLayout} label="支付授权目录：">
                <div>http://www.xiaokeduo.com</div>
              </Form.Item>
              <Row>
                <Col span={3} offset={3}>
                <Button type="primary" onClick={this.handleSubmit} loading={loadbtn}>
                  保存配置
                </Button>
                </Col>
              </Row>
            </Form>
          </Card>
        </Spin>
      </Fragment>
    );
  }
}
export default connect(({ paysetting, global, loading }) => ({
  paysetting,
  oemInfo: global.oemInfo,
  loading: loading.effects['paysetting/GetPayConfig'],
  loadbtn: loading.effects['paysetting/SetPayConfig'],
}))(XcxPay);
